package socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class ByteUtils {

	public static byte[] toBytes(int value) {
		ByteBuffer bufferInt = ByteBuffer.allocate(4);
		bufferInt.putInt(value);
		return bufferInt.array();
	}

	public static int toInt(byte[] bytes, int offset) {
		return toInt(Arrays.copyOfRange(bytes, offset, offset + 4));
	}

	public static int toInt(byte[] bytes) {
		ByteBuffer bufferInt = ByteBuffer.allocate(4);
		bufferInt.put(bytes);
		bufferInt.position(0);
		return bufferInt.getInt();
	}

	public static int toInt(InputStream buffer) throws IOException {
		ByteBuffer bufferInt = ByteBuffer.allocate(4);
		byte[] integer = new byte[4];
		buffer.read(integer);
		bufferInt.put(integer);
		return bufferInt.getInt();
	}

	public static void writeInt(int value, ByteArrayOutputStream buffer) {
		buffer.write(ByteUtils.toBytes(value), 0, 4);
	}

	public static byte[] inputStreamToByte(InputStream in) throws IOException {

		byte[] buffer = new byte[512];
		ByteArrayFastOutputStream output = new ByteArrayFastOutputStream();
		int size = 0;

		while ((size = in.read(buffer)) >= 512) {
			output.write(buffer);
		}

		if (size > 0) {
			output.write(Arrays.copyOf(buffer, size));
		}
		return output.getBytes();
	}
}
